package butines.kraz.state;

import butines.kraz.entity.AbstractState;
import butines.kraz.entity.Unit;

public class UnitChaseToEnemyState extends AbstractState<Unit> {
	
	private static final UnitChaseToEnemyState instance = new UnitChaseToEnemyState();
	
	public static UnitChaseToEnemyState getInstance() {
		return instance;
	}

	@Override
	public void enter(Unit unit) {
		unit.getSteering().getSeek().on(unit.getEnemy().getPosition());
		
		if (unit.getSprite().isAnimation("walk")) {
			unit.getSprite().resume();
		} else {
			unit.getSprite().play("walk");	
		}
		
	}

	@Override
	public void leave(Unit owner) {
		owner.getSteering().getSeek().off();
	}

	@Override
	public void execute(Unit unit) {
		Unit enemy  = unit.getEnemy();
		
		if (enemy == null || enemy.isDied()) {
			unit.stay();
			return;
		}
		
		float minDist = enemy.getRadius() + unit.getRadius() + (unit.getWeapon().getRange() * .7f);
		float curDist = enemy.distance(unit);
		
		boolean canAttackEnemy = curDist <= minDist ;
		
		if (canAttackEnemy) {
			unit.changeState(UnitAttackState.getInstance());
			return;
		}
		
		unit.getSteering().getSeek().getTarget().set(enemy.getPosition());
				
	}
		
}
